package com.ft.statemachine.recipes.persist;

import com.ft.mapper.OrderMapper;
import com.ft.model.Order;
import com.ft.model.enums.OrderStatusChangeEventEnum;
import com.ft.model.enums.OrderStatusEnum;
import com.ft.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.transition.Transition;

import java.util.Optional;

/**
 * @author: zhangjianghua
 * @Date: 2018-10-11 11:16
 */
public class OrderPersistStateChangeListener implements PersistEnumStateMachineHandler.PersistEnumStateChangeListener<OrderStatusEnum, OrderStatusChangeEventEnum> {

    @Autowired
    private OrderService orderService;

    @Override
    public void onPersist(State<OrderStatusEnum, OrderStatusChangeEventEnum> state, Message<OrderStatusChangeEventEnum> message,
                          Transition<OrderStatusEnum, OrderStatusChangeEventEnum> transition, StateMachine<OrderStatusEnum, OrderStatusChangeEventEnum> stateMachine) {
        Optional.ofNullable(message).ifPresent(msg-> Optional.ofNullable(Long.class.cast(msg.getHeaders().getOrDefault("primaryKey", -1L)))
                .ifPresent(orderId->{
                    Order order = new Order();
                    order.setId(orderId);
                    order.setStatus(state.getId());
                    orderService.update(order);
                }));
        /**
         * lambda表达式之前
         */
        /*if (message != null && message.getHeaders().containsKey("id")) {
            Long orderId = message.getHeaders().get("id", Long.class);
            Order order = new Order();
            order.setId(orderId);
            order.setStatus(state.getId());
            orderService.update(order);
        }*/
    }
}
